import json
import logging
from datetime import datetime
from typing import Optional

import requests
import pandas as pd
from django.conf import settings

from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from search_main.utlis import TimeUtils
from search_main.utlis import HttpClient
from search_main.utlis import token_51cto
from search_main.models import Hot51CTO
from search_main.serializers import Hot51CTOSerializer


class ViewsGeekPark(APIView, TimeUtils):
    def __init__(self):
        super().__init__()
        self.http_client = HttpClient()

    def get(self, request):
        try:
            response = self.http_client.get_client(
                url=settings.API_GEEKPARK_URL,
            )
            items = response['data']['homepage_posts']

            processed_data = []
            # with open('1.json', 'w', encoding='utf-8') as f:
            #     f.write(json.dumps(items))
            for item in items:
                item = item.get("post", {})
                processed_data.append({
                    "id": item.get("id", ""),
                    "title": item.get("title", ""),
                    "desc": item.get("abstract", ""),
                    "cover": item.get("cover_url", ""),
                    "author": item.get("authors", [])[0].get("nickname", ""),
                    "timestamp": self.parse_time(item.get("published_timestamp")),
                    "hot": item.get("views", ""),
                    "url": f"https://www.geekpark.net/news/{item.get('id', '')}",
                    "mobile_url": f"https://www.geekpark.net/news/{item.get('id', '')}"
                })
            result = {
                "name": "geekpark",
                "title": "极客公园",
                "type": "热门文章",
                "description": "极客公园聚焦互联网领域，跟踪新鲜的科技新闻动态，关注极具创新精神的科技产品。",
                "link": "https://www.geekpark.net/",
                "total": len(processed_data),
                "data": processed_data,
                "update_time": self.format_time()
            }

            # =================
            print(f"极客公园热榜（共{result['total']}条）:")
            for idx, item in enumerate(processed_data[:10], 1):
                print(f"{idx}. [{item['timestamp']}] {item['title']}")
                print(f"   作者：{item['author']} | 热度：{item['hot']}")
                print(f"   链接：{item['url']}\n")
            # =================

            return Response(result, status=status.HTTP_200_OK)
        except requests.exceptions.RequestException as e:
            print(f"请求失败: {e}")
            return Response(
                {"error": "服务暂不可用"},
                status=status.HTTP_503_SERVICE_UNAVAILABLE
            )